package video;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Timer;

import client.Client;

import others.RTPpacket;
import others.VideoStream;
import others.Constants;

public class Sender extends Thread implements ActionListener {

	String VideoFileName; //video file to request to the server
	String peerIp;
	Client client;
	Socket rtpSocket;
	
	//RTP variables:
	//------------------------------------------------------------------------------------------------------------
	byte[] buf; //buffer used to store data received from the server
	DatagramPacket senddp; //UDP packet containing the video frames
	DatagramSocket RTPsocket; //socket to be used to send and receive UDP packets
    private Sender sender = null;
    InetAddress peerIPAddr; //Peer IP address
    int peerPort;
	//------------------------------------------------------------------------------------------------------------

	//------------------------------------------------------------------------------------------------------------

	//Video constants:
	//------------------------------------------------------------------------------------------------------------
	int MJPEG_TYPE = 26; //RTP payload type for MJPEG video
	VideoStream video; //VideoStream object used to access video frames
	int FRAME_PERIOD = 100; //Frame period of the video to stream, in ms
	int VIDEO_LENGTH = 500; //length of the video in frames
	int STOPED = 1;
	int PLAYED = 2;
	int PAUSED = 3;
	int videostate = STOPED;
	
	Timer timer;
	
	//------------------------------------------------------------------------------------------------------------


    public Sender(InetAddress clientIp,int clientDestPort) {
      this.peerPort =clientDestPort;
      this.peerIPAddr = clientIp;
      
      timer = new Timer(FRAME_PERIOD, this);
      timer.setInitialDelay(0);
      timer.setCoalesce(true);
      buf = new byte[15000];
    }

    public void run() {
    	System.out.println("Entrou na Thread");
    	
		VideoFileName = "D:/eclipse/MyProjects/movie.Mjpeg";
    	//turn videostate to PLAYED
    	videostate=PLAYED;
    	


		//init the VideoStream object
		try {
			video = new VideoStream(VideoFileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		timer.start();
    }
    public void actionPerformed(ActionEvent e) {
    	int framenb = 0;
		
		if(framenb < VIDEO_LENGTH){

			//If videostate was PAUSED then block here
			while (videostate == PAUSED) {
                try {
                    sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
			
			//Increment number of frame to send
			framenb++;

			//Set time between packets to 50 ms
			try {
				Thread.currentThread().sleep(FRAME_PERIOD);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}

			//get next frame to send from the video, as well as its size
			int frame_atual = 0;
			try {
				frame_atual = video.getnextframe(buf);
			} catch (Exception e2) {
				e2.printStackTrace();
			}

			//Builds an RTPpacket object containing the frame
			RTPpacket rtp_packet = new RTPpacket(MJPEG_TYPE, framenb, framenb*FRAME_PERIOD, buf, frame_atual);

			//get to total length of the full rtp packet to send
			int packet_length = rtp_packet.getlength();

			//retrieve the packet bitstream and store it in an array of bytes
			byte[] packet_bits = new byte[packet_length];
			rtp_packet.getpacket(packet_bits);

			senddp = new DatagramPacket(packet_bits, packet_length, peerIPAddr, peerPort);

			//send the packet as a DatagramPacket over the UDP socket
			try {
				DatagramSocket sc1 = new DatagramSocket();
				sc1.send(senddp);
			} catch (IOException e3) {
				e3.printStackTrace();
			}

			//print RTP header
				rtp_packet.printheader();	       
		}
		
		//turn videostate to STOPED
		videostate=STOPED;
		
		//sends STOP message to server 
	//	send_NP_request("STOP");*************************************************************
		
		//destroys sender
		sender = null;
    }
       
}